package org.jssvc.opac

import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.util.Log
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.palette.graphics.Palette
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import kotlinx.android.synthetic.main.activity_book_details.*
import org.json.JSONObject
import org.jssvc.opac.bean.Content
import org.jssvc.opac.data.Constant
import org.jssvc.opac.data.DataFormatUtils
import org.jssvc.opac.data.JsoupUtils
import org.jssvc.opac.fragment.TextFragment


class BookDetailsActivity : AppCompatActivity() {

    val fragments = ArrayList<Fragment>()
    val titles = ArrayList<String>()
    var boonBean: Content? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_book_details)
        BarUtils.setStatusBarLightMode(this, true) // StatusBar黑色文字

        boonBean = intent.getSerializableExtra("bean") as Content

        initToolBar()

        loadBaseInfo2UI()

        getBookDetailsByISBN(boonBean?.isbn!!)

        getBookStoreInfo(boonBean?.marcRecNo!!)
    }

    private fun initToolBar() {
        setSupportActionBar(tool_bar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.setDisplayShowTitleEnabled(false)

        tool_bar.title = boonBean?.title
        tool_bar.setNavigationOnClickListener {
            onBackPressed()
        }
    }

    // 加载默认数据
    private fun loadBaseInfo2UI() {
        // 添加基础信息
        titles.add(getString(R.string.book_details_tag_base))
        var intro = DataFormatUtils.getBookIntro(this, boonBean!!)
        fragments.add(TextFragment.newInstance(getString(R.string.book_details_tag_base), intro))

        loadBookCover("") // 加载空图片

        refreshTabLayout()
    }

    /**
     * 获取库存
     */
    private fun getBookStoreInfo(marc_no: String) {
        OkGo.get<String>(Constant.api_book_store_info)
            .params("marc_no", marc_no)
            .execute(object : StringCallback() {
                override fun onSuccess(response: Response<String>?) {
                    var html = response?.body().toString()
                    val list = JsoupUtils.parseBookStoreInfo(html)
                    if (list.isNullOrEmpty()) return

                    if (fragments.size > 0) {
                        titles.removeAt(0)
                        fragments.removeAt(0)
                    }

                    var callNo = list[0].callNo as String
                    var intro = DataFormatUtils.getBookIntro(this@BookDetailsActivity, boonBean!!)
                    if (list.isNotEmpty()) {
                        intro += "\n" + getString(R.string.book_details_call_no) + "$callNo"
                    }
                    intro += "\n"
                    intro += DataFormatUtils.getBookStoreIntro(list)

                    titles.add(0, getString(R.string.book_details_tag_base))
                    fragments.add(
                        0,
                        TextFragment.newInstance(
                            getString(R.string.book_details_tag_base),
                            intro,
                            callNo
                        )
                    )

                    refreshTabLayout()
                }

                override fun onError(response: Response<String>?) {
                    super.onError(response)
                }
            })
    }

    /**
     * 获取图书详情
     */
    private fun getBookDetailsByISBN(isbn: String) {
        OkGo.get<String>(Constant.api_book_details_by_isbn + isbn)
            .execute(object : StringCallback() {
                override fun onSuccess(response: Response<String>?) {
                    var jo = JSONObject(response?.body())
                    if (jo.has("code")) {
                        ToastUtils.showShort(jo.optString("msg"))
                        onBackPressed()
                    } else {
                        loadData2UI(jo)
                    }
                }

                override fun onError(response: Response<String>?) {
                    super.onError(response)
                }
            })

    }

    /**
     * 加载图片
     */
    private fun loadData2UI(jo: JSONObject) {
        var coverUrl = jo.optString("image")
        loadBookCover(coverUrl)

        var strSummary = jo.optString("summary")
        var strAuthorIntro = jo.optString("author_intro")
        var strCatalog = jo.optString("catalog")


        if (strSummary != "") {
            titles.add(getString(R.string.book_details_tag_summary))
            fragments.add(
                TextFragment.newInstance(
                    getString(R.string.book_details_tag_summary),
                    strSummary
                )
            )
        }
        if (strAuthorIntro != "") {
            titles.add(getString(R.string.book_details_tag_author))
            fragments.add(
                TextFragment.newInstance(
                    getString(R.string.book_details_tag_author),
                    strAuthorIntro
                )
            )
        }
        if (strCatalog != "") {
            titles.add(getString(R.string.book_details_tag_catalogue))
            fragments.add(
                TextFragment.newInstance(
                    getString(R.string.book_details_tag_catalogue),
                    strCatalog
                )
            )
        }

        refreshTabLayout()
    }

    // 更新标签页
    private fun refreshTabLayout() {
        view_pager.adapter = object : FragmentStatePagerAdapter(supportFragmentManager) {
            override fun getItem(position: Int): Fragment {
                return fragments[position]
            }

            override fun getCount(): Int {
                return fragments.size
            }

            override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
                super.destroyItem(container, position, `object`)
            }

            override fun getPageTitle(position: Int): CharSequence? {
                return titles[position]
            }
        }
        view_pager.offscreenPageLimit = fragments.size
        tab_layout.setupWithViewPager(view_pager)
    }

    // 加载图片
    private fun loadBookCover(url: String) {
        Glide.with(this)
            .asBitmap()
            .load(url)
            .placeholder(R.drawable.ic_book_cover)
            .error(R.drawable.ic_book_cover)
            .into(object : CustomTarget<Bitmap>() {
                override fun onLoadCleared(placeholder: Drawable?) {
                }

                override fun onResourceReady(bitmap: Bitmap, transition: Transition<in Bitmap>?) {
                    if (bitmap == null) {
                        return
                    }
                    iv_book_cover?.setImageBitmap(bitmap)

                    Palette.from(bitmap).maximumColorCount(10)
                        .generate { palette ->
                            //获取某种特性颜色的样品
                            // Swatch lightVibrantSwatch = palette.getLightVibrantSwatch();
                            val swatch = palette?.vibrantSwatch
                            //谷歌推荐的：图片的整体的颜色rgb的混合值---主色调
                            val rgb = swatch?.rgb ?: resources.getColor(R.color.colorPrimary)
                            //谷歌推荐：图片中间的文字颜色
                            val bodyTextColor = swatch?.bodyTextColor ?: Color.WHITE
                            //谷歌推荐：作为标题的颜色（有一定的和图片的对比度的颜色值）
                            val titleTextColor = swatch?.titleTextColor ?: Color.WHITE

                            tool_bar?.setTitleTextColor(titleTextColor) // 貌似无效

                            iv_book_cover?.setBackgroundColor(rgb)
                            BarUtils.setStatusBarColor(this@BookDetailsActivity, rgb);
//                            BarUtils.transparentStatusBar(this@BookDetailsActivity)
                        }
                }
            })
    }
}
